from django.shortcuts import redirect
from rest_framework.response import Response
from rest_framework.views import APIView
from alipay import AliPay
from alipay.utils import AliPayConfig
from django.views import View

class PayView(APIView):
    def post(self, request):
        sn = request.data.get("sn")  # 订单号
        total = request.data.get("total")  # 总金额

        alipay_public_key = open("ThreePayment/alipay/alipay_public_key.txt").read()  # 支付宝公钥
        app_private_key = open("ThreePayment/alipay/app_private_key.txt").read()  # 应用私钥

        alipay = AliPay(
            appid="2021000116660428",
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True,  # 默认False
            config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
        )
        # 如果你是 Python 3的用户，使用默认的字符串即可
        subject = "测试订单支付"

        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=sn,  # 订单号
            total_amount=total,  # 总金额
            subject=subject,  # 标题
            return_url='http://localhost:8000/back',
            # notify_url="https://example.com/notify"  # 可选, 不填则使用默认notify url
        )
        print(sn)
        # 生成一个支付超链接，返回给vue端， 点击就激活这个超链接, 就是支付宝网关
        url = "https://openapi.alipaydev.com/gateway.do?" + order_string
        return Response({"url": url})


class AliPayBackView(View):
    def get(self, request):
        #  获取 支付宝交易号
        trade_no = request.GET.get("trade_no")
        print("trade_no:", trade_no)
        return redirect("http://127.0.0.1:8080/#/paysuccess?trade_no=" + trade_no)
